import 'package:flutter/material.dart';
import '../../domain/entities/favorite.dart';
import '../../domain/entities/anime.dart';
import '../../domain/repositories/favorite_repository.dart';

/// 收藏状态管理Provider
class FavoriteProvider extends ChangeNotifier {
  final FavoriteRepository _repository;

  FavoriteProvider(this._repository);

  // 状态变量
  List<Favorite> _favorites = [];
  Map<FavoriteStatus, List<Favorite>> _favoritesByStatus = {};
  Map<FavoriteStatus, int> _favoriteStats = {};
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';

  // Getters
  List<Favorite> get favorites => _favorites;
  Map<FavoriteStatus, List<Favorite>> get favoritesByStatus => _favoritesByStatus;
  Map<FavoriteStatus, int> get favoriteStats => _favoriteStats;
  bool get isLoading => _isLoading;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;

  /// 获取特定状态的收藏列表
  List<Favorite> getFavoritesByStatus(FavoriteStatus status) {
    return _favoritesByStatus[status] ?? [];
  }

  /// 获取收藏总数
  int get favoriteCount => _favorites.length;

  /// 初始化收藏数据
  Future<void> initializeFavorites() async {
    await loadAllFavorites();
    await loadFavoriteStats();
  }

  /// 加载所有收藏
  Future<void> loadAllFavorites() async {
    _setLoading(true);
    _clearError();

    try {
      _favorites = await _repository.getAllFavorites();
      await _loadFavoritesByStatus();
      notifyListeners();
    } catch (e) {
      _setError('加载收藏失败: ${e.toString()}');
    } finally {
      _setLoading(false);
    }
  }

  /// 按状态分组加载收藏
  Future<void> _loadFavoritesByStatus() async {
    _favoritesByStatus.clear();
    
    for (final status in FavoriteStatus.values) {
      try {
        final statusFavorites = await _repository.getFavoritesByStatus(status);
        _favoritesByStatus[status] = statusFavorites;
      } catch (e) {
        _favoritesByStatus[status] = [];
      }
    }
  }

  /// 加载收藏统计
  Future<void> loadFavoriteStats() async {
    try {
      _favoriteStats = await _repository.getFavoriteStats();
      notifyListeners();
    } catch (e) {
      _setError('加载统计失败: ${e.toString()}');
    }
  }

  /// 添加收藏
  Future<bool> addFavorite(Anime anime, [FavoriteStatus? status]) async {
    try {
      await _repository.addFavorite(anime, status);
      await loadAllFavorites();
      await loadFavoriteStats();
      return true;
    } catch (e) {
      _setError('添加收藏失败: ${e.toString()}');
      return false;
    }
  }

  /// 移除收藏
  Future<bool> removeFavorite(int animeId) async {
    try {
      await _repository.removeFavorite(animeId);
      await loadAllFavorites();
      await loadFavoriteStats();
      return true;
    } catch (e) {
      _setError('移除收藏失败: ${e.toString()}');
      return false;
    }
  }

  /// 更新收藏状态
  Future<bool> updateFavoriteStatus(int animeId, FavoriteStatus newStatus) async {
    try {
      await _repository.updateFavoriteStatus(animeId, newStatus);
      await loadAllFavorites();
      await loadFavoriteStats();
      return true;
    } catch (e) {
      _setError('更新状态失败: ${e.toString()}');
      return false;
    }
  }

  /// 更新观看进度
  Future<bool> updateWatchedEpisodes(int animeId, int watchedEpisodes) async {
    try {
      await _repository.updateWatchedEpisodes(animeId, watchedEpisodes);
      await loadAllFavorites();
      return true;
    } catch (e) {
      _setError('更新进度失败: ${e.toString()}');
      return false;
    }
  }

  /// 更新个人评分
  Future<bool> updatePersonalScore(int animeId, double score) async {
    try {
      await _repository.updatePersonalScore(animeId, score);
      await loadAllFavorites();
      return true;
    } catch (e) {
      _setError('更新评分失败: ${e.toString()}');
      return false;
    }
  }

  /// 更新备注
  Future<bool> updateNotes(int animeId, String notes) async {
    try {
      await _repository.updateNotes(animeId, notes);
      await loadAllFavorites();
      return true;
    } catch (e) {
      _setError('更新备注失败: ${e.toString()}');
      return false;
    }
  }

  /// 检查是否已收藏
  Future<bool> isFavorite(int animeId) async {
    try {
      return await _repository.isFavorite(animeId);
    } catch (e) {
      return false;
    }
  }

  /// 获取特定动漫的收藏信息
  Future<Favorite?> getFavorite(int animeId) async {
    try {
      return await _repository.getFavorite(animeId);
    } catch (e) {
      return null;
    }
  }

  /// 清除所有收藏
  Future<bool> clearAllFavorites() async {
    try {
      await _repository.clearAllFavorites();
      await loadAllFavorites();
      await loadFavoriteStats();
      return true;
    } catch (e) {
      _setError('清除收藏失败: ${e.toString()}');
      return false;
    }
  }

  /// 搜索收藏
  Future<List<Favorite>> searchFavorites(String query) async {
    try {
      // 如果是FavoriteRepositoryImpl，支持搜索
      if (_repository is dynamic) {
        return await (_repository as dynamic).searchFavorites(query);
      }
      
      // 否则在本地过滤
      if (query.isEmpty) return _favorites;
      
      final lowerQuery = query.toLowerCase();
      return _favorites.where((favorite) {
        return favorite.anime.title.toLowerCase().contains(lowerQuery) ||
               favorite.anime.titleJapanese.toLowerCase().contains(lowerQuery) ||
               (favorite.anime.titleEnglish?.toLowerCase().contains(lowerQuery) ?? false);
      }).toList();
    } catch (e) {
      _setError('搜索失败: ${e.toString()}');
      return [];
    }
  }

  /// 获取最近添加的收藏
  Future<List<Favorite>> getRecentFavorites({int limit = 10}) async {
    try {
      if (_repository is dynamic) {
        return await (_repository as dynamic).getRecentFavorites(limit: limit);
      }
      
      // 本地排序
      final sortedFavorites = List<Favorite>.from(_favorites);
      sortedFavorites.sort((a, b) => b.addedDate.compareTo(a.addedDate));
      return sortedFavorites.take(limit).toList();
    } catch (e) {
      return [];
    }
  }

  /// 按状态刷新特定分类的收藏
  Future<void> refreshFavoritesByStatus(FavoriteStatus status) async {
    try {
      final statusFavorites = await _repository.getFavoritesByStatus(status);
      _favoritesByStatus[status] = statusFavorites;
      notifyListeners();
    } catch (e) {
      _setError('刷新收藏失败: ${e.toString()}');
    }
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  /// 设置错误状态
  void _setError(String message) {
    _hasError = true;
    _errorMessage = message;
    notifyListeners();
  }

  /// 清除错误状态
  void _clearError() {
    _hasError = false;
    _errorMessage = '';
  }

  /// 快速切换收藏状态 (用于详情页面)
  Future<bool> toggleFavorite(Anime anime, {FavoriteStatus? defaultStatus}) async {
    final isCurrentlyFavorite = await isFavorite(anime.id);
    
    if (isCurrentlyFavorite) {
      return await removeFavorite(anime.id);
    } else {
      return await addFavorite(anime, defaultStatus ?? FavoriteStatus.wantToWatch);
    }
  }
} 